<?php
namespace app\controller\admin;

use app\BaseController;
use app\lib\Password;
use app\lib\response\JSON;
use app\model\User as ModelUser;
use app\Request;
use app\validate\User as UserValidator;
use think\exception\ValidateException;

class User extends BaseController
{
    
    /**
     * 用户信息
     */
    public function userInfo(Request $r)
    {
        $user = ModelUser::with(['role'])->find($r->session['uid']);
        return JSON::successData([
            'name' => $user->username,
            'avatar' => $user->avatar,
            'roles' =>  $user->role ? [$user->role->name] : [],
        ]);
        
    }

    public function logout(){
        return JSON::success();
    }

    public function list()
    {
       $list = ModelUser::order('create_time','desc')->with(['role' => function($query){
               $query->withField([
                   'id',
                   'name'
               ]);
           }])->paginate();
        return JSON::page($list->total(),$list->items());
    }

    //添加用户
    public function add(Request $r){
        $params = $r->post();
        try {
            validate(UserValidator::class)
                ->scene('add')
                ->check($params);
        } catch (ValidateException $e) {
            return JSON::error($e->getMessage());
        }
        //检查用户名是否存在
        $exists = ModelUser::where('username',$params['username'])->value('id');
        if($exists){
            return JSON::error("用户名已存在");
        }
        //插入数据库
        $user = new ModelUser();
        $user->username = $params['username'];
        $user->password = Password::encrypt($params['password']);
        $user->status = $params['status'];
        $user->role_id = $params['role_id'];
        $user->avatar = $params['avatar'] ?? "";
        $user->save();
        return JSON::success("添加成功");
    }

    public function edit(Request $r){
        $params = $r->post();
        try {
            validate(UserValidator::class)
                ->scene('edit')
                ->check($params);
        } catch (ValidateException $e) {
            return JSON::error($e->getMessage());
        }
        //检查用户是否存在
        $user = ModelUser::find($params['id']);
        if(!$user){
            return JSON::error("用户不存在");
        }
        //更新数据库
        $params['password'] && $user->password=Password::encrypt($params['password']);
        $user->status = $params['status'];
        $user->role_id = $params['role_id'];
        $user->avatar = $params['avatar'] ?? "";
        $user->save();
        return JSON::success("修改成功");
    }

    public function delete(Request $r){
        $params = $r->post();
        try {
            validate(UserValidator::class)
                ->scene('delete')
                ->check($params);
        } catch (ValidateException $e) {
            return JSON::error($e->getMessage());
        }
        ModelUser::destroy($params['id']);
        return JSON::success("已删除");
    }

}
